package cn.cai.controller;


import cn.cai.commonUtils.Result;
import cn.cai.exceptionHandler.GuliException;
import cn.cai.pojo.EduTeacher;
import cn.cai.pojo.vo.QueryTeacher;
import cn.cai.service.IEduTeacherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author caishenao
 * @since 2021-08-04
 */
@Api(value="讲师controller",tags="讲师操作接口")
@RestController
@RequestMapping("/eduservice/teacher")
@CrossOrigin
public class EduTeacherController {
    @Autowired
    private IEduTeacherService eduTeacherService;

    @GetMapping("/queryAll")
    @ApiOperation(value = "查询所有讲师")
    public Result queryAll(){
        List<EduTeacher> list = eduTeacherService.list();
        return Result.success().data("list",list);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除指定id的讲师")
    public Result deleted(@PathVariable("id") String id){
        boolean flag = eduTeacherService.removeById(id);
        return Result.success().data("flag",flag).data("msg","删除成功");
    }
    //实现教师分页的业务
    @GetMapping("/pageTeacher/{currentPage}/{pageSize}")
    @ApiOperation(value = "讲师查询的分页操作")
    public Result pageTeacher(@PathVariable("currentPage") Integer currentPage,
                              @PathVariable("pageSize") Integer pageSize){
        if (currentPage == null && pageSize == null){   //进行简单的数据校验
            currentPage = 1;        //设置空参请求时的默认值
            pageSize = 5;
        }
        Page<EduTeacher> teacherPage = new Page<>(currentPage,pageSize);
        Page<EduTeacher> page = eduTeacherService.page(teacherPage);    //返回结果

        return Result.success().data("page",page);
    }

    //实现多条件组合分页查询教师

    @GetMapping("/pageTeacherCondition/{currentPage}/{pageSize}")
    @ApiOperation(value = "get请求实现多条件分页查询")
    public Result pageTeacherCondition(@PathVariable("currentPage") Long currentPage,
                                       @PathVariable("pageSize") Long pageSize,
                                       QueryTeacher queryTeacher){
        //这里写的业务逻辑判断应该写到service层，但为了方便先写到controller层
        //创建
        QueryWrapper<EduTeacher> queryWrapper = new QueryWrapper<>();
        String name = queryTeacher.getName();       //得到用户请求发来的名字
        String id = queryTeacher.getId();           //得到用户请求发来的教师id
        Integer sort = queryTeacher.getSort();      //得到用户请求发来的排序
        LocalDateTime begin = queryTeacher.getBegin();  //得到用户请求发来的教师创建时间
        LocalDateTime end = queryTeacher.getEnd();  //得到用户发来的教师的结束时间
        if (!StringUtils.isEmpty(name)){
            queryWrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(id)){
            queryWrapper.eq("id",id);
        }
        if (!StringUtils.isEmpty(sort)){
            queryWrapper.eq("sort",sort);
        }


        //后两项因为现在是单表操作，所以先比较表里的数据，然后再比较链表数据
        if (!StringUtils.isEmpty(begin)){
            queryWrapper.le("gmt_create",begin);
        }
        if (!StringUtils.isEmpty(end)){
            queryWrapper.ge("gmt_modified",end);
        }
        //使用MP的wapper进行条件查询
        Page<EduTeacher> teacherPage = new Page<>(currentPage,pageSize);
        //调用service层的方法
        Page<EduTeacher> page = eduTeacherService.page(teacherPage, queryWrapper);
        //返回查询的数据
        return Result.success().data("page",page);
    }
    //POST请求实现多条件组合分页
    @PostMapping("/pageTeacherConditionForPost/{currentPage}/{pageSize}")
    @ApiOperation(value = "post请求实现讲师多条件分页查询")
    public Result pageTeacherConditionForPost(@PathVariable("currentPage") Long currentPage,
                                              @PathVariable("pageSize") Long pageSize,
                                              @RequestBody QueryTeacher queryTeacher){

        //这里写的业务逻辑判断应该写到service层，但为了方便先写到controller层
        //创建
        QueryWrapper<EduTeacher> queryWrapper = new QueryWrapper<>();
        String name = queryTeacher.getName();       //得到用户请求发来的名字
        String id = queryTeacher.getId();           //得到用户请求发来的教师id
        Integer sort = queryTeacher.getSort();      //得到用户请求发来的排序
        Integer level = queryTeacher.getLevel();        //得到用户请求发来的头衔
        LocalDateTime begin = queryTeacher.getBegin();  //得到用户请求发来的教师创建时间
        LocalDateTime end = queryTeacher.getEnd();  //得到用户发来的教师的结束时间
        if (!StringUtils.isEmpty(name)){
            queryWrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(id)){
            queryWrapper.eq("id",id);
        }
        if (!StringUtils.isEmpty(sort)){
            queryWrapper.eq("sort",sort);
        }
        if(!StringUtils.isEmpty(level)){
            queryWrapper.eq("level",level);
        }
        /**
         * 后两项因为现在是单表操作，所以先比较表里的数据，然后再比较链表数据
         */
        if (!StringUtils.isEmpty(begin)){
            queryWrapper.le("gmt_create",begin);
        }
        if (!StringUtils.isEmpty(end)){
            queryWrapper.ge("gmt_modified",end);
        }
        //按照创建时间的倒叙查询
        queryWrapper.orderByDesc("gmt_create");
        //使用MP的wapper进行条件查询
        Page<EduTeacher> teacherPage = new Page<>(currentPage,pageSize);
        //调用service层的方法
        Page<EduTeacher> page = eduTeacherService.page(teacherPage, queryWrapper);
        //返回查询的数据
        return Result.success().data("page",page);
    }

    @PostMapping("/addTeacher")
    @ApiOperation(value = "增加讲师")
    public Result addTeacher(@RequestBody EduTeacher eduTeacher){
        boolean save = false;
        try {
            save = eduTeacherService.save(eduTeacher);
        }catch (Exception e){
            return Result.error().data("msg","讲师名不能相同");
        }
        return save?Result.success().data("flag",save).data("msg","保存成功"):Result.error();
    }

    //根据讲师id查询全部信息
    @GetMapping("/queryTeacherById/{id}")
    @ApiOperation(value = "根据讲师的id查询讲师的信息")
    public Result queryTeacherById(@PathVariable("id") String id){
        EduTeacher queryTeacher = eduTeacherService.getById(id);
        if (queryTeacher != null){
            return Result.success().data("queryTeacher",queryTeacher);
        }else {
            return Result.error().data("msg","抱歉，查无此人");
        }
    }
    //因为数据库中name字段添加了唯一约束，所以在修改的时候，名字不能够重复
    @GetMapping("/foundSame/{id}/{name}")
    @ApiOperation(value = "查询id值下的name是否已经存在，用于修改讲师名字使用")
    public Result foundTheSame(@PathVariable("id") String id,
                               @PathVariable("name") String name){
        QueryWrapper<EduTeacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("id",id);
        queryWrapper.eq("name",name);
        List<EduTeacher> list = eduTeacherService.list(queryWrapper);
        if (list.size() == 0){
            return Result.success().data("msg","教师名字可用");
        }else return Result.error().data("msg","教师名字重复");
    }
    //根据传入的teacher对象，修改数据库中讲师的信息
    @PostMapping("/modifyTeacher")
    @ApiOperation(value = "修改讲师")
    public Result modifyTeacher(@RequestBody EduTeacher eduTeacher){
        QueryWrapper<EduTeacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",eduTeacher.getId());
        //这里不做校验
        boolean update = eduTeacherService.update(eduTeacher, queryWrapper);
        return update?Result.success().data("msg","修改成功"):Result.error().data("msg","修改失败");
    }

    @GetMapping("/errorEx")
    public Result error(){
        try {
            int a = 10 / 0;
        }catch (Exception e){
            throw new GuliException(20001,"服务器处理异常");
        }
        return Result.success();
    }

}
